<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Support\Code;
use App\Http\Requests\Request;

class ResetPasswordController extends ApiController
{
    public function index(Request $request)
    {
        $user = User::where('name', $request->name)->first();
        if (!$user) {
            return $this->fail(Code::PARAMETER_ERROR, '用户名不存在！');
        }

        if (is_string($request->mnemonic_word)) {
            $mnemonic_word = json_decode($request->mnemonic_word, true);
        } else {
            $mnemonic_word = $request->mnemonic_word;
        }

        if ($mnemonic_word !== $user->mnemonic_word) {
            return $this->fail(Code::PARAMETER_ERROR, '助记词错误');
        }

        $user->password = $request->password;
        $user->save();

        return $this->setMsg('修改成功！')->success();
    }
}
